<?php


namespace App\Services\Core\Traits;


use App\Exceptions\ErrResponse;

trait Response
{
    # 正确号
    public array $successMsg = [10000 => '操作成功'];
    # 错误号
    public array $errorMsg = [20000 => '操作失败', 20001 => '验证失败'];
    # 逻辑成功
    public int $successStatus = 200;
    # 逻辑失败
    public int $errorStatus = 500;
    # 未登录
    public int $loginStatus = 401;
    # 权限不足
    public int $authStatus = 403;
    # 三方失败
    public int $extStatus = 428;
    # 重定向
    public int $redirectStatus = 302;

    public function fail(string $msg = '',$result = null, int $status = null, int $code = 20000)
    {
        return throw new ErrResponse(json_encode($this->setData($result, $status ?? $this->errorStatus, $code, $msg)));
    }

    public function success($result = true, int $code = 10000, string $msg = '')
    {
        return $this->setData($result, $this->successStatus, $code, $msg);
    }

    public function result($result ,int $code = 10000 , string $msg = '')
    {
        $status = $this->successStatus;
        if(!$result){
            $code = 20000;
            $status = $this->errorStatus;
        }
        return $this->setData($result,$status,$code,$msg);
    }

    private function setData($result, int $status = null, int $code, string $msg)
    {
        $this->setMsg();

        return [
            'status' => $status,
            'code'   => $code,
            'msg'    => '' !== $msg ? $msg : $this->getMsg($code),
            'result' => $result,
        ];
    }


    private function getMsg(int $code)
    {
        return isset($this->errorMsg[$code]) ? $this->errorMsg[$code] : $this->successMsg[$code];
    }

    public function setMsg()
    {
    }

}
